package com.rr.middle;

import com.rr.entity.TreeNode;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zhuangcanrun
 * @Date 2022/08/22/19:00
 * @description
 **/

/*
* https://leetcode.cn/problems/zhong-jian-er-cha-shu-lcof/submissions/
* 给出先序和中序遍历结果，构建出树
* */
public class BuildTree {

    Map<Integer, Integer> indexMap = new HashMap<>();

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        int length = inorder.length;
        for (int i = 0; i < length; i++) {
            indexMap.put(inorder[i], i);
        }
        return getAns(preorder, inorder, 0, length - 1, 0, length - 1);
    }

    private TreeNode getAns(int[] preorder, int[] inorder, int preorderLeft, int preorderRight, int inorderLeft, int inorderRight) {
        if (preorderLeft > preorderRight) {
            return null;
        }

        //在中序遍历中root结点所在的下标位置，即先序遍历的第一个结点
        int rootIndexInInorder = indexMap.get(preorder[preorderLeft]);
        //左子树的结点个数=中序遍历的root结点下标-中序遍历的左界
        int leftNum = rootIndexInInorder - inorderLeft;

        TreeNode root = new TreeNode(preorder[preorderLeft]);
        //构建左子树，即先序遍历的root后下一个结点+左子树结点数，中序遍历的左界到root结点下标-1
        root.left = getAns(preorder, inorder, preorderLeft + 1, preorderLeft + leftNum, inorderLeft, rootIndexInInorder - 1);
        //构建右子树，即先序遍历root的左子树之后的结点，右结点左办为root+1，右界就原先的右界
        root.right = getAns(preorder, inorder, preorderLeft + leftNum + 1, preorderRight, rootIndexInInorder + 1, inorderRight);
        return root;
    }

    public static void main(String[] args) {
        BuildTree buildTree = new BuildTree();
        System.out.println(buildTree.buildTree(new int[]{3, 9, 20, 15, 7}, new int[]{9, 3, 15, 20, 7}));
    }
}
